﻿/*
*  知识结构
* 
* 
*/
var kdManagement = angular.module("kdStructure", ['ui.tree', 'Common', 'knowledgebaseS','knowledgeSelector', 'loadModule', 'knowledgeStructureAddEdit','btnconqitk','knowledgeDeleteBox'])
.controller('kdStructure', ['$scope','$rootScope','sysUserInfo', 'RequestTrainService', 'Comm', 'MsgCon', 'Msg', function ($scope,$rootScope,sysUserInfo, RTS, Comm, MsgCon, Msg) {
    $scope.btnlist={savefun:false,addinfo:false,editinfo:false,delinfo:false,addmodel:false};
    $rootScope.btnTab = "index.Train.kngframe";
   
    // 初始化
    $scope.init = function () {
        $scope.knowledgeLoading = false;
        $scope.soso=false;
        $scope.knowledgeList = [];   //知识结构列表
        $scope.selectAll = 0;
        $scope.queryAll = 0;
        $scope.params = {
            userId: sysUserInfo.getuserinfo().user_ID,
            startDate: "",    // 起始时间
            endDate: "", // 结束时间
            searchName: "", //搜索内容 
            knowledge_Id: "", // 子集搜索
            orgId: sysUserInfo.getuserinfo().organization_ID,   // 企业id
            org_Name: sysUserInfo.getuserinfo().organization_Name,   // 企业id
            powerLV: sysUserInfo.getuserinfo().powerLV //登录人的系统角色         
        };

        $scope.getList();
    }
    // 执行回车
    $scope.findlistbyEnter = function (e) {
        var keycode = window.event ? e.keyCode : e.which;
        if (keycode == 13) {
            $scope.soso=true;
            $scope.getList();
        }
    }
    // 给时间赋值
    $scope.GetDate = function () {
        $scope.params.startDate = document.getElementById("startDate").value;
        $scope.params.endDate = document.getElementById("endDate").value;
    }
    //展开/折叠
    $scope.openNode = function (obj, knode) {
        if (!obj.collapsed && knode.haschildren > 0) { // 展开时请求服务器  并且存在子节点。
            knode.btnLoadingShow = true;
            if (knode.children != null && knode.children.length > 0) { // 之前是有值的
                var ids = [];
                var sum = 0;
                sum = $scope.getSelId(knode.children, ids, "null", sum);
                //console.log(ids.length);    // 选中的节点中所有的子节点
                //console.log(sum);    //此节点下的所有的节点
                $scope.selectAll -= ids.length;
                $scope.queryAll -= sum;
            }
            $scope.params.knowledge_Id = knode.knowledge_Id;
            $scope.params.searchName = "";
            $scope.params.startDate = "";
            $scope.params.endDate = "";
             RTS.findKnowledgeList($scope.params).then(function (response) {  // then
                //$scope.knowledgeLoading = false;
                knode.btnLoadingShow = false;
                if (response.errorcode == "0") {
                    knode.children = response.datas;
                    angular.forEach(knode.children, function (data) {
                        data.parentName = knode.knowledge_Name;
                    });
                    $scope.queryAll += response.datas.length;
                    //$scope.selectAll = 0                    
                    //开始获取负者人                   
                    $scope.findUserByKnowledge(knode.children);                                   
                }
            });
        }
        obj.toggle();
    }
    // 全选、 取消
    $scope.checkAll = function () {
        if ($scope.selectAll == $scope.queryAll) { // 全选状态  取消全选
            angular.forEach($scope.knowledgeList, function (data, index, array) {
                data.isFlag = false;
                $scope.checkAllNode(data.children, false);
            });
            $scope.selectAll = 0;
        } else {    // 全选
            angular.forEach($scope.knowledgeList, function (data, index, array) {
                data.isFlag = true;
                $scope.checkAllNode(data.children, true);
            });
            $scope.selectAll = $scope.queryAll;
        }
    }
    // 选中子节点\ 递归选中所有
    $scope.checkAllNode = function (list, flag) {
        angular.forEach(list, function (data, index, array) {
            data.isFlag = flag;
            $scope.checkAllNode(data.children, flag);
        });
    }
    // 选中单个
    $scope.checkSingle = function (item) {
        //        console.log(item);
        //$scope.paramsadd = item;
        if (item.isFlag) {
            $scope.selectAll--;
            item.isFlag = false;
        } else {
            $scope.selectAll++;
            item.isFlag = true;
        }
        return false;
    }
    /* 
    *   获取选中的id
    *    list   循环的list
    *    SelIds 选中id
    * selItems 选中的item  没有必须为 “null”
    *    countSum 总节点数
    *   返回一总子节点数
    */
    $scope.getSelId = function (list, selIds, selItems, countSum) {
        angular.forEach(list, function (data, index, array) {
            countSum = countSum + 1;
            if (data.isFlag) {
                selIds.push(data.knowledge_Id);
                if (selItems != "null") { //  禁止添加
                    selItems.push(data);
                } else {
                    selItems = "null";
                }
            }
            $scope.getSelId(data.children, selIds, selItems, countSum);
        });
        return countSum;
    }
    /*
    *获取对象
    *   id 节点id
    *   response
    *   obj
    */
    $scope.getObj = function (list, id, obj) {
        angular.forEach(list, function (data, index, array) {
            if (data.knowledge_Id == id) {
                obj = data
            }
            $scope.getObj(data.children, id, obj);
        });
        return obj;
    }
    //获取列表
    $scope.getList = function () {
        $scope.knowledgeLoading = true; // 更换为圆圈的loading
        //        console.log($scope.params);
        if (($scope.params.searchName == null || $scope.params.searchName == "" || $scope.params.searchName == undefined)
        && ($scope.params.startDate == null || $scope.params.startDate == "" || $scope.params.startDate == undefined)
        && ($scope.params.endDate == null || $scope.params.endDate == "" || $scope.params.endDate == undefined)) {
            $scope.params.knowledge_Id = null;
        }

//        if($scope.params.startDate!= "" || $scope.params.endDate!="" || $scope.params.searchName!= ""){$scope.soso=true;}

          RTS.findKnowledgeList($scope.params).then(function (response) {
            $scope.knowledgeLoading = false;  //关闭loading
            if (response.errorcode == "0") {// 成功       
                $scope.knowledgeList = response.datas;
                $scope.queryAll = response.datas.length;                
                //开始获取负者人
                $scope.findUserByKnowledge($scope.knowledgeList);               
            } else {   // 获取失败 
                Msg.error("获取失败！");
            }
        }, function errorCallback() {
            $scope.knowledgeLoading = false;  //关闭loading
            //            console.log("连接服务器失败！");
            Msg.error("连接服务器失败！");
        });
    }
    //获取负者人列表
    $scope.findUserByKnowledge = function (data) {
            var knowledgeUser={knowledge:[]};
            var datas={knowledge_Id:""};
            angular.forEach(data, function (data) {
                    datas.knowledge_Id=data.knowledge_Id;
                    knowledgeUser.knowledge.push(datas);
                    datas={knowledge_Id:""};
             });              
              RTS.findUserByKnowledge(knowledgeUser).then(function (response) {
                if (response.errorcode == "0") {// 成功       
                    angular.forEach(response.datas, function (userdata) {
                        angular.forEach(data, function (knowledgedata) {
                             if(knowledgedata.knowledge_Id==userdata.knowledge_Id){
                                    knowledgedata.ulist=userdata.ulist;
                             }
                        });
                      });
                } else {   // 获取失败 
                    Msg.error("获取失败！");
                }
            }, function errorCallback() {
                Msg.error("连接服务器失败！");
            });
        }
     // 删除信息框的显示隐藏    
    $scope.deleteHide = false; //隐藏状态
    // 隐藏 用于指令回调
    $scope.cancelHide = function(){
        $scope.deleteHide = false; 
    }
    //$scope.deleteList.length = 0;    
    $scope.knowledgeItem=null;

    $scope.para = {knowledge_Id: [],orgID: sysUserInfo.getuserinfo().organization_ID, sortCode: "", userId: sysUserInfo.getuserinfo().user_ID, delparentId: [],confirmdel:"" };
    // 删除
    $scope.delinfo = function (item,index) {
        if(index!=0&&index!=undefined&&index!=null){
            item=$scope.knowledgeItem;
        }else{
            $scope.knowledgeItem=item;
        }
        $scope.para.delparentId=[];
        var SelIds = [];
        var selParentIds = [];
        var selItems = [];
        if (!Comm.isNull(item)) { //单个删除
            SelIds.push(item.knowledge_Id);
            selParentIds.push(item.parentId);
        } else {
            $scope.getSelId($scope.knowledgeList, SelIds, selItems, 0);
            angular.forEach(selItems, function (data) {
                selParentIds.push(data.parentId);
            });
       }
        $scope.para.knowledge_Id=SelIds;
        $scope.para.confirmdel=index;
        //        console.log(SelIds);
        if (SelIds == null || SelIds == undefined || SelIds.length <= 0) {
            Msg.warning("请至少选中一行数据！");
            return;
        }
       if(index==0 || index=="0"||index==undefined||index==null||index==""){
            //提示框
            MsgCon.delnoicon().then(function (flag) {   // 删除弹框
                if (flag) {
                    $scope.knowledgeLoading = true; 
                    $scope.delcenter($scope.para);
                }
            })
       }else if(index==2 || index=="2"){
           //提示框
            MsgCon.delnoicon("删除提示","删除的数据将永久丢失，不可找回，确定删除吗？").then(function (flag) {   // 删除弹框
                if (flag) {
                   $scope.knowledgeLoading = true; 
                $scope.delcenter($scope.para);
                }
            })
       }
    }
    $scope.delcenter=function(para){
            RTS.delKnowledge(para).then(function (response) {
                    $scope.knowledgeLoading = false;  //关闭loading
                    if (response.errorcode == "0" && response.numCount > 0) {// 成功       
                        Msg.success("删除成功！");
                        $scope.knowledgeItem=null;
                        $scope.deleteHide = false; 
                        $scope.init();
                    } else if (response.errorcode == "34") {   // 获取失败                                         
                        $scope.deleteList = response.datas;
                        $scope.deleteHide = true;   // 显示关联窗口
                    } else {   // 获取失败 
                        Msg.error("删除失败！");
                    }
                },function errorCallback() {
                    Msg.error("连接服务器失败！");
                }
          );
    }

    /************************************************添加编辑知识结构**************************************/
    $scope.knowledgesHide = false; //添加、修改知识架构弹框初始
    $scope.knowledgeLoading = false; // 更换为圆圈的loading
    // 创造一个知识结构对象   
    $scope.knowledgeInfoInit = {
        userId: sysUserInfo.getuserinfo().user_ID,
        userName: sysUserInfo.getuserinfo().user_Name,
        create_Id: sysUserInfo.getuserinfo().user_ID,
        create_Name: sysUserInfo.getuserinfo().user_Name,
        org_ID: sysUserInfo.getuserinfo().organization_ID,   // 企业id
        org_Name: sysUserInfo.getuserinfo().organization_Name,   // 企业id
        knowledge_Name: "",
        knowledge_Type: "",
        knowledge_Id: "0", // 子集搜索
        parentId: "0",
        parentName: "父节点",
        introduction: "",
        classification: "0",
        sortCode: "0",
        userIds: [],
        ulist:[],
        OrgId: sysUserInfo.getuserinfo().organization_ID,   // 企业id
        OrgName: sysUserInfo.getuserinfo().organization_Name,
        powerLV: sysUserInfo.getuserinfo().powerLV //登录人的系统角色         
    };
    $scope.kList = [];  // 父节点
    //新增
      $scope.addinfo=function(){
        $scope.addkonwledge();
  }
    
    // 初始化赋值
    //$scope.knowledgeInfo = angular.copy($scope.knowledgeInfoInit);
    //添加    item 对象  type ： 1新增节点  2新增子节点 
    $scope.addkonwledge = function (item, type) {
        if (type == 2) {    // 新增子节点
            $scope.knowledgeInfo = angular.copy($scope.knowledgeInfoInit); // 重新初始化子节点参数
            //$scope.knowledgeInfo.classification = item.classification+1;    //节点级数 这个可在保存处理
            $scope.kList[0] = { knowledge_Id: item.knowledge_Id, knowledge_Name: item.knowledge_Name, classification: (item.classification==undefined?0:item.classification-1) };  // 绑定父节点
            $scope.knowledgesHide = true;
            return;
        }
        if (item != null && item != undefined && item != "") {  // 单独的编辑
            $scope.kList[0] = { knowledge_Id: item.parentId, knowledge_Name: item.parentName, classification: (item.classification==undefined?0:item.classification-1) };  // 绑定父节点
            $scope.knowledgeInfo = angular.copy(item);
            if (item.parentName != undefined) {
                $scope.kList[0] = { knowledge_Id: item.parentId, knowledge_Name: item.parentName, classification:(item.classification==undefined?0:item.classification-1 ) };  // 绑定父节点
            } else {
                $scope.kList[0] = { knowledge_Id: item.parentId, knowledge_Name: "父节点", classification: 0 };  // 绑定父节点
            }
            $scope.knowledgesHide = true;
            return;
        }
        var selIds = [];
        var selItems = [];
        $scope.getSelId($scope.knowledgeList, selIds, selItems, 0);
        //初始化新增
        if (selIds == null || selIds == undefined || selIds.length <= 0) { // 新增            
            $scope.knowledgeInfo = angular.copy($scope.knowledgeInfoInit);
            // console.log($scope.knowledgeInfo);
            $scope.kList[0] = { knowledge_Id: "0", knowledge_Name: "", classification: 0 };  // 绑定父节点
            //$scope.kList[0] = angular.copy({ knowledge_Id: "0", knowledge_Name: "父节点" });  // 绑定父节点
        } else if (selIds != null && selIds != undefined && selIds.length == 1) {
            $scope.knowledgeInfo = angular.copy(selItems[0]);
            $scope.kList[0] = { knowledge_Id: selItems[0].parentId, knowledge_Name: selItems[0].parentName,classification: (selItems[0].classification==undefined?0:selItems[0].classification-1 ) };  // 绑定父节点
        } else if (selIds != null && selIds != undefined && selIds.length > 1) {
            Msg.warning("请只选择一条操作记录！");
            return;
        }
        //console.log($scope.knowledgeInfo);
        $scope.knowledgesHide = true;
    }

    //取消
    $scope.addhide = function () {
        $scope.knowledgesHide = false;
        $scope.isModelShow = false;
    }
    //添加、修改、移动 addOrUpKnowledge
    $scope.saveKnowledge = function (item) {
    
        if (item.parentId == item.knowledge_Id && item.knowledge_Id != "0") {
            Msg.warning("不能选择自身节点为父节点！");
            return;
        }
        if (item.knowledge_Name == null || item.knowledge_Name == "" || item.knowledge_Name == undefined) {
            Msg.info("知识架构名称不能为空！");
            return;
        }
        if (Comm.isNull(item.parentId)) {
            item.parentId = "0";
        }
        //        console.log(item);
        console.log(item);
        
        // 整理人员数据
        item.userIds = [];
        angular.forEach(item.ulist, function (data, index, array) {
            item.userIds.push(data.user_ID);
        });
        item.powerLV = sysUserInfo.getuserinfo().powerLV;
        $scope.knowledgeLoading = true; // 更换为圆圈的loading
        // 发送请求
        RTS.addOrUpKnowledge(item).then(function (response) {
            $scope.knowledgeLoading = false;  //关闭loading
            if (response.errorcode == "0") {// 成功       
                Msg.success("保存成功！");
                $scope.addhide();
                $scope.init();
            } else {   // 获取失败 
                Msg.error("操作失败！");
            }
        }, function errorCallback() {
            $scope.knowledgeLoading = false;  //关闭loading
            //            console.log("连接服务器失败！");
            Msg.error("连接服务器失败！");
        });
    }
    /********************************************模版弹出********************************************/
    $scope.isModelShow = false;
    //$scope.paramodel = { "model_Id": "0" }; //模板参数初始化
    //$scope.modelobj = { "modelLV": "", "modelId": "", "modelName": "", "parentId": "" };
    $scope.modelList = []; //模板列表
    $scope.modelHashId = [];
    //$scope.conModelList = [];
    //匹配指令新增
    $scope.addmodel=function(){
        $scope.addModel();
    }
    //模板弹框------先查询，再弹出
    $scope.addModel = function () {
        $scope.knowledgeLoading = false;  //关闭loading
        //$scope.paramodel.model_Id = 0;
        //$scope.getModellist($scope.paramodel);        
        $scope.isModelShow = true;
    }
    //    $scope.getModellist = function (paramm) {
    //        $scope.knowledgeLoading = true; // 更换为圆圈的loading
    //        RTS.findModelList(paramm).then(function (response) {
    //            $scope.operateLoading = false;  //关闭loading
    //            if (response.errorcode == "0") {// 成功       
    //                $scope.ModelList = response.datas;
    //            } else {   // 获取失败 
    //                Msg.error("获取失败！");
    //            }
    //        }, function errorCallback() {
    //            $scope.knowledgeLoading = false;  //关闭loading
    //            console.log("连接服务器失败！");
    //        });

    //    }
    //    //根据父节点查询  子模板
    //    $scope.findmodelbyfid = function (modelId) {
    //        $scope.modelList = [];
    //        $scope.paramodel.model_Id = modelId.model_Id;
    //        //设置参数
    //        $scope.modelobj.modelId = modelId.model_Id;
    //        $scope.modelobj.modelLV = modelId.model_Level;
    //        $scope.modelobj.modelName = modelId.model_Name;
    //        $scope.modelobj.parentId = modelId.parentId;

    //        $scope.modelList.push($scope.modelobj);
    //        $scope.modelobj = { "modelLV": "", "modelId": "", "modelName": "", "parentId": "" };
    //        $scope.getModellist($scope.paramodel);
    //    }  
    //    //向模板集合添加项
    //    $scope.addToList = function (modelinfo) {
    //        //设置参数
    //        $scope.modelobj.modelId = modelinfo.model_Id;
    //        $scope.modelobj.modelLV = modelinfo.model_Level;
    //        $scope.modelobj.modelName = modelinfo.model_Name;
    //        $scope.modelobj.parentId = modelinfo.parentId;

    //        $scope.modelList.push($scope.modelobj);
    //        $scope.modelobj = { "modelLV": "", "modelId": "", "modelName": "", "parentId": "" };
    //        console.log($scope.modelList);
    //    }
    //保存模板  
    $scope.saveModel = function (item) {
        $scope.isModelShow = false;
        $scope.init();
//        return; //以下在指令中运行
/*
        item = {
            powerLV: sysUserInfo.getuserinfo().powerLV,
            userId: sysUserInfo.getuserinfo().user_ID,
            userName: sysUserInfo.getuserinfo().username,
            OrgId: sysUserInfo.getuserinfo().organization_ID,   // 企业id
            OrgName: sysUserInfo.getuserinfo().organization_Name,
            modelObj: $scope.modelList,
            delmodelObj: [],
            isEdit: false//添加-fasle，编辑-true
        };
//        console.log(item);        
        $scope.knowledgeModelLoading = true; // 更换为圆圈的loading
        
        RTS.addModelKnowledge(item).then(function (response) {
            $scope.knowledgeModelLoading = false;  //关闭loading
            if (response.errorcode == "0") {// 成功       
                Msg.success("保存成功！");
                $scope.isModelShow = true; //模板弹框初始
                $scope.init();
            } else {   // 获取失败 
                Msg.error("操作失败！");
            }
        }, function errorCallback() {
            $scope.knowledgeModelLoading = false;  //关闭loading
            //            console.log("连接服务器失败！");
            Msg.error("连接服务器失败！");
        });*/
    }
    /******************************************(预留)移动***************************************************/
             //配置知识选择器
     $scope.knowConfig = {   // 配置知识选择器的参数
                menu: ["structure"],
                kssMore:false, //知识结构 是否多选
                kssList:[],    // 知识结构选中列表
                isShow:false,  // 显示知识选择器
      };          
    $scope.movekonwledge=function(knode){
        $scope.knowConfig.isShow=true;
    }
/***************************************************************************************************/
    //人员选择器
    $scope.showPersonSelect = function () {
        $scope.ApiData.ApiOpen = true;
    }
    $scope.init();
} ]);
